#include "stdafx.h"
#include "Shader.h"
#include "Utils.h"

cShader::cShader(): m_ID(-1), m_program(0), m_vertexShader(0), m_fragmentShader(0)
{
	memset(m_fileVertexShader, '\0', MAX_LENGTH_NAME);
	memset(m_fileFragmentShader, '\0', MAX_LENGTH_NAME);
	m_state &= STATE_NONE;
}

cShader::cShader(int id, const char *fileVertexShader, const char *fileFragmentShader, int state)
{
	cShader();

	m_ID = id;
	m_state = state;

	int i = 0;
	while(fileVertexShader[i] != '\0')
	{
		m_fileVertexShader[i] = fileVertexShader[i];
		i++;
	}

	i = 0;
	while(fileFragmentShader[i] != '\0')
	{
		m_fileFragmentShader[i] = fileFragmentShader[i];
		i++;
	}
}

cShader::~cShader()
{
	glDeleteProgram(m_program);
	glDeleteShader(m_vertexShader);
	glDeleteShader(m_fragmentShader);
}

int cShader::Init()
{
	if (m_program > 0) //already init
	{
		return 0;
	}

	char *fvs_url = JoinString(SHADERS_PATH, m_fileVertexShader);
	char *ffs_url = JoinString(SHADERS_PATH, m_fileFragmentShader);

	m_vertexShader = esLoadShader(GL_VERTEX_SHADER, fvs_url);
	SAFE_DEL_ARRAY(fvs_url);

	if ( m_vertexShader == 0 )
	{
		glDeleteShader(m_vertexShader);
		return -1;
	}


	m_fragmentShader = esLoadShader(GL_FRAGMENT_SHADER, ffs_url);
	SAFE_DEL_ARRAY(ffs_url);

	if ( m_fragmentShader == 0 )
	{
		glDeleteShader(m_fragmentShader);
		return -2;
	}

	m_program = esLoadProgram(m_vertexShader, m_fragmentShader);

	return 0;
}
